<template>
  <div>
    <el-card style="margin:20px 20px">
      <CategorySelect :disabled="!isList" />
    </el-card>
    <el-card style="margin:20px 20px">
      <!-- 这是属性列表的结构 -->
      <div v-show="isList">
        <el-button :disabled="!category3Id" type="primary" size="small" icon="el-icon-plus" @click="showAddAttr">添加属性值</el-button>
        <el-table
          :data="attrList"
          border
          style="width: 100%"
        >
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          />
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150"
          />
          <el-table-column
            label="属性值名称列表"
          >
            <template v-slot="{row}">
              <el-tag v-for="attrValue in row.attrValueList" :key="attrValue.id" type="success">{{ attrValue.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template v-slot="{row}">
              <el-button
                size="mini"
                icon="el-icon-edit-outline"
                title="修改属性"
                style="margin-right:10px"
                @click="showUpdateAttr(row)"
              />
              <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" icon="el-icon-info" icon-color="red" title="这是一段内容确定删除吗" @onConfirm="deleteTrademark(row)">
                <el-button slot="reference" icon="el-icon-delete" type="danger" size="small" title="删除" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 这是添加属性的结构 -->
      <div v-show="!isList">
        <el-form inline>
          <el-form-item label="属性名">
            <el-input v-model="attrForm.attrName" placeholder="请输入属性名" />
          </el-form-item>
        </el-form>
        <el-button :disabled="!attrForm.attrName" type="primary" size="default" @click="addAttrValue">添加属性值</el-button>
        <el-button size="default" @click="isList = true">取消</el-button>
        <el-table :data="attrForm.attrValueList" border style="margin-top: 20px;">
          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input
                v-if="row.isEdit"
                v-model="row.valueName"
                :input-ref="inputRef"
                size="small"
                @keyup.enter="toLook(row, $index)"
                @blur="toLook(row, $index)"
              />
              <span
                v-else
                style="display: block; width: 100%"
                @click="toEdit(row)"
              >{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                :title="`你确定要删除${row.valueName}这个属性值吗?`"
                @onConfirm="deleteAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    title="删除属性值"
                    icon="el-icon-delete"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          :disabled="!attrForm.attrValueList.length"
          type="primary"
          size="default"
          @click="addOrUpdateAttr"
        >保存</el-button>
        <el-button
          size="default"
          @click="isList = true"
        >取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import CategorySelect from '@/components/CategorySelect/index.vue'
import { reqAttrsList } from '@/api/product/attr'
import { mapState } from 'vuex'

import cloneDeep from 'lodash/cloneDeep'
import { saveAttr, deleteAttr } from '@/api/product/attr'
export default {
  name: 'Attr',
  components: {
    CategorySelect
  },
  data() {
    return {
      isList: true,
      attrList: [],
      inputRef: '',
      attrForm: {
        attrName: '',
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 0
      }
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  watch: {
    category3Id: {
      handler(newVal) {
        if (!newVal) {
          this.attrList = []
        } else {
          this.getAttrList(this.category1Id, this.category2Id, this.category3Id)
        }
      },
      immediate: true
    }

  },

  methods: {
    async getAttrList() {
      const res = await reqAttrsList(this.category1Id, this.category2Id, this.category3Id)
      this.attrList = res.data
    },
    // 点击添加属性
    showAddAttr() {
      this.isList = false
      this.attrForm = {
        attrName: '',
        attrValueList: [],
        categoryId: this.category3Id,
        categoryLevel: 3
      }
    },
    // 点击添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        isEdit: true,
        valueName: '',
        attrId: this.attrForm.id
      })
      this.$nextTick(() => {
        this.inputRef.focus()
      })
    },
    // 点击修改属性
    showUpdateAttr(row) {
      this.isList = false
      this.attrForm = cloneDeep(row)
      row.attrValueList.forEach((item) => {
        item.isEdit = false
      })
    },
    toEdit(row) {
      row.isEdit = true
      this.$nextTick(() => {
        this.inputRef.focus()
      })
    },
    // input失去焦点进入查看模式
    toLook(row, index) {
      if (!row.valueName.trim()) {
        this.attrForm.attrValueList.splice(index, 1)
        return
      }
      const flag = this.attrForm.attrValueList.some((item) => {
        if (item !== row) {
          return row.valueName === item.valueName
        }
      })
      if (flag) {
        this.$message.error('输入的属性值名称不能重复')
        this.attrForm.attrValueList.splice(index, 1)
        return
      }
      row.isEdit = false
    },
    // 删除属性值 不需要发送请求
    deleteAttrValue(index) {
      this.attrForm.attrValueList.splice(index, 1)
    },
    // 保存的逻辑
    async addOrUpdateAttr() {
      const attr = this.attrForm
      attr.attrValueList = attr.attrValueList.filter((item) => {
        if (item.valueName.trim()) {
          delete item.isEdit
          return true
        }
      })
      if (!attr.attrValueList.length) {
        this.$message.error('确保有属性值')
        return
      }
      try {
        await saveAttr(attr)
        this.$message.success(`${attr.id ? '修改' : '添加'}属性成功`)
        this.isList = true
        this.getAttrList()
      } catch (error) {
        this.$message.error(`${attr.id ? '修改' : '添加'}属性失败`)
      }
    },
    // 删除属性的逻辑
    async deletAttr(row) {
      try {
        await deleteAttr(row.id)
        this.$message.success('删除属性成功')
        this.getAttrList()
      } catch (error) {
        this.$message.error('删除属性失败')
      }
    }
  }

}
</script>

<style lang="less" scoped>

</style>
